package org.inspiration.dudu.web.interceptor;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.inspiration.dudu.common.constant.Constant;
import org.inspiration.dudu.common.exception.ServiceException;
import org.inspiration.dudu.common.util.JwtUtil;
import org.inspiration.dudu.user.model.vo.UserVO;
import org.inspiration.dudu.user.service.UserService;
import org.inspiration.dudu.user.util.UserContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();


        // 从请求头获取 token
        String token = request.getHeader("Authorization");
        // 验证token
        if (StrUtil.isBlank(token) || !jwtUtil.verifyToken(token)) {
            throw new ServiceException(Constant.UNAUTHORIZED_ERROR_CODE, Constant.USER_NOT_AUTHENTICATED);
        }
        //记录当前请求的用户信息
        UserVO userVO = userService.getUserByToken(token);
        UserContextUtil.setUserVO(userVO);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理
        UserContextUtil.clear();
    }
}
